const CONSTANT = require('../../constant/Constant');
const webim = require('../../component/webim-component/webim_wx');
const { config } = require('../../../common/utils/ws/ws-config.js');
const {
  getOpenID,
  getUserInfo,
} = require('../../../common/utils/ws/wsxcx-opendata-sdk');
let app = getApp();
Page({
  data: {
    template: 'videomode',
    sdkAppID: '',
    userID: '',
    userSig: '',
    roomID: '',
    teacherId: '',
    privateMapKey: '',
    isHorizontal: false,
    inputMsg: '',
    toview: '',
    messageList: [],
    timeoutID: null,
    isAllow: false,
    maxAllow: 10,
    pushMode: 'audio',
    linkedMembers: [],
    currentTab: 'message',
    boardLoaded: false,
    online: -1,
    userName: '',
    tapTime: '',
    isServer: false, // 验证服务
    linkable: false,
    linked: false,
    playerMuted: false,
    muted: true,
    isWifi: true,
    linkDialogVisible: false,
  },

  imUserAvatars: {},

  onLoad: function (options) {
    for (const key in options) {
      if (options.hasOwnProperty(key)) {
        options[key] = decodeURIComponent(options[key]);
      }
    }
    this.data.roomID = options.roomID;
    this.options = options;
    
    const teacherId = `webrtc_${options.username}`;
    wx.setNavigationBarTitle({
      title: `${options.name}`,
    });
    this.setData({
      teacherId,
      isAllow: options.is_allow == '1',
      maxAllow: Number(options.max_allow || 10),
      pushMode: options.pushMod,
      roomInfo: options,
    },()=> {
      this.data.isServer = true;
      this.setScreenOn();
      this.checkAuthorize();
    });
  },

  onShow() {
    this.setScreenOn();
  },

  onUnload() {
    wx.setKeepScreenOn({
      keepScreenOn: false,
    });
    this.txTic && this.txTic.quitClassRoom(() => {
      if (webim.checkLogin()) {
        webim.logoutAll();
      }
    });
    if (this.data.timeoutID) {
      clearTimeout(this.data.timeoutID);
    }
  },

  setScreenOn() {
    let { isServer } = this.data;
    if (isServer) {
      wx.setKeepScreenOn({
        keepScreenOn: true,
      });
    }
  },

  checkAuthorize() { // 检查用户是否已授权 为了后台能拿到头像昵称，这里需要强制授权一次
    getUserInfo()
      .then(userInfo => {
        const sys = wx.getSystemInfoSync();
        this.data.userName = userInfo.nickName;
        this.setData({
          roomID: this.options.roomID || '',
          isWide: (sys.windowWidth / sys.windowHeight) > 9 / 16,
        }, () => {
          let pages = getCurrentPages();
          let route = pages[pages.length - 1].route;
          app.videoVisiterRecord(this.data.roomID, route.split('/')[0]);
            this.init();
        });
      })
      .catch(res => {
        this.setData({
          isShow: true,
        });
      });
  },

  getUserInfo(e) {
    this.checkAuthorize();
  },

  enter() {
    let nowTime = new Date();
    if (nowTime - this.data.tapTime < 1000) {
      return;
    }
      this.init();
    this.data.tapTime = nowTime;
  },

  init() {
    wx.getNetworkType({
      success: (res) => {
        const networkType = res.networkType;
        this.setData({ isWifi: networkType === 'wifi' }, () => {
          if (this.data.isWifi) {
              this.initWebrtc();
          }
        });
      },
    });
  },

  initWithoutWifi() {
    this.setData({ isWifi: true });
      this.initWebrtc();
  },

  initWebrtc() {
    let sdkAppID;
    let userID;
    this.txTic = this.selectComponent('#tx_board');
    this.webrtcroomComponent = this.selectComponent('#webrtcroom');
    this.getLoginData().then(loginData => {
      sdkAppID = loginData.sdkAppID;
      userID = loginData.userID;
      return this.login(loginData);
    }).then(() => {
      this.joinClassRoom().catch(() => {
        this.setData({ online: false });
      });
      return this.getPrivateMapKey(userID, this.data.roomID);
    }).then(data => {
      console.log('====音视频对话开始======');
      // 通过更新 page 上的属性 5 个属性后，则可以启动推流。
      this.setData({
        sdkAppID,
        userID: data.userID,
        userSig: data.userSig,
        roomID: this.data.roomID,
        privateMapKey: data.privateMapKey,
      }, () => {
        this.webrtcroomComponent.start();
        this.postRecord();
      });
    }).catch(() => {
      console.error('Failed to init.');
    });
  },

  getLoginData() {
    // 请求后台登陆接口获取user登陆信息
    return new Promise((resolve, reject) => {
      app.util.request({
        url: 'entry/wxapp/tic',
        cachetime: '0',
        data: {
          op: 'login',
        },
        module: 'cm_onlineclass',
        success: res => {
          if (res.data.errno === 0) {
            resolve(res.data.data);
          } else {
            reject(res);
          }
        },
        fail: res => {
          console.error('Failed to get login data: ', res);
          reject(res);
        },
      });
    });
  },

  getPrivateMapKey(userID, roomID) {
    return new Promise((resolve, reject) => {
      app.util.request({
        url: 'entry/wxapp/tic',
        cachetime: '0',
        data: {
          op: 'getprivateMapKey',
          userID,
          roomID,
        },
        module: 'cm_onlineclass',
        success: res => {
          if (res.data && res.data.errno === 0 && res.data.data) {
            resolve(res.data.data);
          } else {
            reject(res);
          }
        },
        fail: res => {
          console.error('Failed to get privateMapKey: ', res);
          reject(res);
        },
      });
    });
  },

  login(loginData) {
    const userName = this.data.userName || loginData.userID;
    // tic 组件登录接口登录
    return new Promise((resolve, reject) => {
      Promise.all([
        getOpenID(),
        getUserInfo(),
      ]).then(([openID, userInfo]) => {
        this.txTic.login({
          sdkAppId: loginData.sdkAppID,
          identifier: loginData.userID,
          identifierNick: userName,
          identifierAvatar: userInfo.avatarUrl || userInfo.wxInfo.avatarUrl || '',
          selfSignature: openID || '',
          userSig: loginData.userSig,
        }, () => {
          console.log('====登陆初始化======');
          this.imUserAvatars[loginData.userID] = userInfo.avatarUrl || userInfo.wxInfo.avatarUrl || '';
          resolve();
        }, (err) => {
          console.error('tic login failed: ', err);
          reject(err);
        });
      });
    });
  },

  joinClassRoom() {
    return new Promise((resolve, reject) => {
      this.txTic.joinClassRoom(this.data.roomID, () => {
        console.log('====加入课堂======');
        // 初始化白板
        console.log('====初始化白板开始======');
        this.txTic.initBoard({ orientation: this.data.isHorizontal ? 'horizontal' : 'vertical' });
        resolve();
      }, (err) => {
        console.error('Failed to join classroom: ', err);
        reject(err);
      });
    });
  },

  postRecord() {
    app.util.request({
      url: 'entry/wxapp/tic',
      data: {
        op: 'postRecord',
        roomid: this.data.roomID,
      },
      module: 'cm_onlineclass',
      success: res => {
        console.log('post record', this.data.roomID);
      },
    });
  },

  bindInputMsg(e) {
    this.setData({
      inputMsg: e.detail.value,
    });
  },

  sendMessage() {
    const inputMsg = this.data.inputMsg;
    if (inputMsg && inputMsg.trim()) {
      app.util.request({
        url: 'entry/wxapp/tic',
        data: {
          op: 'postComment',
          roomid: this.data.roomID,
          comment: inputMsg,
        },
        module: 'cm_onlineclass',
        success: res => {
          if (res.data.errno === 0) {
            this.txTic.sendGroupTextMsg(inputMsg, () => {
              console.log('消息发送成功: ', inputMsg);
            }, (code, err) => {
              console.log('消息发送失败: ', code, err);
              wx.showToast({
                icon: 'none',
                title: '消息发送失败',
              });
            });
          } else {
            console.error('check comment status: ', res);
            wx.showToast({
              icon: 'none',
              title: res.data.message,
            });
          }
        },
        fail: res => {
          console.error('Failed to check comment status: ', res);
          if (res.data.errno === -1) {
            wx.showToast({
              icon: 'none',
              title: res.data.message,
            });
          }
        },
        complete: () => {
          this.setData({ 
            // showInput: false, 
            inputMsg: '', 
          });
        },
      });
    } else {
      wx.showToast({
        icon: 'none',
        title: '不能发送空消息',
      });
    }
  },

  changePlayerMuted() {
    this.webrtcroomComponent.changePlayerMuted();
  },
  onPlayerMutedChange(e) {
    this.setData({ playerMuted: e.detail.playerMuted });
  },
  changeMuted() {
    this.webrtcroomComponent.changeMuted();
  },
  onMutedChange(e) {
    this.setData({ muted: e.detail.muted });
  },
  requestJoinPusher() {
    this.webrtcroomComponent.requestJoinPusher();
  },

  /**
   * 请求连麦
   */
  onRequestJoinPusher() {
    console.log('onRequestJoinPusher() called');
    if (this.data.requestLinking) {
      wx.showToast({
        title: '等待老师接受连麦',
        duration: 1000,
      });
      return;
    }
    console.info('用户请求连麦');
    this.data.requestLinking = true;
    if (this.data.timeoutID) {
      clearTimeout(this.data.timeoutID);
      this.data.timeoutID = null;
    }
    this.data.timeoutID = setTimeout(() => {
      this.data.requestLinking = false;
    }, 10000);

    const body = {
      cmd: 'linkmic',
      data: {
        type: 'request',
        roomID: this.data.roomID,
        userID: this.data.userID,
        userName: this.data.userName || this.data.userID,
        userAvatar: this.data.userAvatar || '',
      },
    };
    const msg = {
      data: JSON.stringify(body),
    };
    this.txTic.sendC2CCustomMsg(this.data.teacherId, msg, (ret) => {
      this.data.requestLinking = false;
      if (ret && !ret.errCode) {
        console.log('已发送连麦请求:', ret);
        wx.showToast({
          icon: 'none',
          title: '已发送连麦请求',
        });
      } else {
        console.error('连麦请求发送失败:', ret);
        wx.showToast({
          icon: 'none',
          title: '连麦请求发送失败',
        });
      }
    });
  },

  recvC2CMsg(msg) {
    console.log('收到C2C消息:', JSON.stringify(msg));
    const contentObj = JSON.parse(msg.content);
    if (contentObj) {
      if (contentObj.cmd == 'linkmic') {
        if (contentObj.data && contentObj.data.type == 'response') {
          if (contentObj.data.result == 'accept') {
            wx.showToast({
              icon: 'none',
              title: '老师接受了你的连麦请求',
            });
            this.webrtcroomComponent.startLink();
          } else if (contentObj.data.result == 'reject') {
            wx.showToast({
              icon: 'none',
              title: '老师拒绝了你的连麦请求',
            });
          }
        } else if (contentObj.data && contentObj.data.type == 'invite') {
          // 收到老师连麦请求
          this.setData({ linkDialogVisible: true });
        } else if (contentObj.data && contentObj.data.type == 'kickout') {
          wx.showToast({
            icon: 'none',
            title: '被老师下麦',
          });
          this.webrtcroomComponent.quitLink();
        }
      }
    }
  },

  startLink() {
    this.webrtcroomComponent.startLink();
    this.cancelLink();
  },

  cancelLink() {
    this.setData({ linkDialogVisible: false });
  },

  getAvatar(accountId) {
    return new Promise((resolve, reject) => {
      const avatar = this.imUserAvatars[accountId];
      if (avatar) {
        resolve(avatar);
      } else {
        webim.getProfilePortrait(
          {
            To_Account: [accountId],
            TagList: ['Tag_Profile_IM_Image'],
          },
          (resp) => {
            if (resp.UserProfileItem && resp.UserProfileItem.length > 0) {
              const avatar = resp.UserProfileItem[0].ProfileItem[0].Value;
              this.imUserAvatars[accountId] = avatar;
              resolve(avatar);
            } else {
              resolve(null);
            }
          },
          (err) => {
            console.log(err);
            resolve(null);
          }
        );
      }
    });
  },

  onPusherJoined() {
    const body = {
      cmd: 'linkmic',
      data: {
        type: 'response',
        result: 'joined',
        userID: this.data.userID,
      },
    };
    const msg = {
      data: JSON.stringify(body),
    };
    this.txTic.sendC2CCustomMsg(this.data.teacherId, msg);
    this.setData({ linked: true });
  },

  onPusherQuitted() {
    const body = {
      cmd: 'linkmic',
      data: {
        type: 'response',
        result: 'quitted',
        userID: this.data.userID,
      },
    };
    const msg = {
      data: JSON.stringify(body),
    };
    this.txTic.sendC2CCustomMsg(this.data.teacherId, msg);
    this.setData({ linked: false });
  },

  onLinkableChange(e) {
    this.setData({ linkable: e.detail.linkable });
  },

  onIMEvent(e) {
    const { tag, code, detail = {}} = e.detail;
    console.log(tag, code, detail);
    const fromAccount = detail.fromAccount || '';
    const nickName = detail.fromAccountNick || fromAccount;
    /* eslint-disable no-case-declarations */
    switch (tag) {
      case CONSTANT.IM.BIG_GROUP_MSG_NOTIFY:
        console.log('收到大群消息通知');
        break;
      case CONSTANT.IM.MSG_NOTIFY:
        console.log('收到普通群消息');
        const sessType = detail.getSession().type();
        const subType = detail.getSubType();
        switch (sessType) {
          case webim.SESSION_TYPE.C2C:
            switch (subType) {
              case webim.C2C_MSG_SUB_TYPE.COMMON:// c2c普通消息
                // 业务可以根据发送者帐号fromAccount是否为app管理员帐号，来判断c2c消息是否为全员推送消息，还是普通好友消息
                // 或者业务在发送全员推送消息时，发送自定义类型(webim.MSG_ELEMENT_TYPE.CUSTOM,即TIMCustomElem)的消息，在里面增加一个字段来标识消息是否为推送消息
                const contentHtml = this.txTic.convertMsgtoHtml(detail);
                // c2c消息一定要调用已读上报接口
                const opts = {
                  To_Account: fromAccount, // 好友帐号
                  LastedMsgTime: detail.getTime(), // 消息时间戳
                };
                webim.c2CMsgReaded(opts);
                this.recvC2CMsg({
                  fromAccountNick: nickName,
                  content: contentHtml,
                });
                console.log('收到一条c2c消息(好友消息或者全员推送消息): 发送人=' + nickName + ', 内容=' + contentHtml);
                break;
            }
            break;
          case webim.SESSION_TYPE.GROUP:
            switch (subType) {
              case webim.GROUP_MSG_SUB_TYPE.COMMON:
                if (detail.elems && detail.elems instanceof Array) {
                  detail.elems.forEach(ele => {
                    if (ele.type === 'TIMTextElem') {
                      this.getAvatar(fromAccount).then(avatar => {
                        this.setData({
                          messageList: this.data.messageList.concat([{
                            type: 'msg',
                            from: nickName,
                            fromId: fromAccount,
                            fromAvatar: avatar,
                            content: ele.content.text,
                          }]),
                          toview: null, // 滚动条置底
                        });

                        this.setData({
                          toview: 'scroll-bottom', // 滚动条置底
                        });
                      });
                    } else if (ele.type === 'TIMCustomElem') {
                      const data = JSON.parse(ele.content.getData());
                      if (data.cmd === 'linkmic' && data.data && data.data.type === 'members') {
                        this.setData({
                          linkedMembers: data.data.result,
                        });
                      }
                    }
                  });
                }
                break;
            }
            break;
        }
        break;
      case CONSTANT.IM.KICKED:
        console.log('被踢下线');
        wx.showToast({
          icon: 'none',
          title: '被踢下线',
        });
        break;
      case CONSTANT.IM.GROUP_SYSTEM_NOTIFYS:
        const eventType = code.event_type;
        if (eventType === webim.GROUP_SYSTEM_TYPE.DESTORY) {
          this.setData({ online: false }, () => {
            wx.showModal({
              title: '提示',
              content: '主播已下线~',
              showCancel: false,
              confirmText: '确定',
              confirmColor: '#3CC51F',
            });

          });
        }
        break;
    }
  },
  onBoardEvent(e) {
    const {
      tag,
      data,
    } = e.detail;
    console.log(tag, data);
    switch (tag) {
      // 白板 SDK 鉴权不通过
      case CONSTANT.BOARD.VERIFY_SDK_ERROR:
        break;
      case CONSTANT.BOARD.VERIFY_SDK_SUCC:
        this.setData({ boardLoaded: true });
        break;
    }
  },
  onRoomEvent(e) {
    const { tag, code, detail } = e.detail;
    console.log(tag, code, detail);
    switch (code) {
      case CONSTANT.ROOM.PLAYER_LOADING:
        this.setData({ online: true });
        break;
      case CONSTANT.ROOM.PLAYER_PLAY:
        this.setData({ online: true });
        break;
      case CONSTANT.ROOM.PLAYER_DISCONNECT:
        this.setData({ online: false });
        break;
      case CONSTANT.ROOM.ERROR_OPEN_CAMERA:
        console.log('打开摄像头失败');
        break;
    }
  },
  switchOrientation() {
    this.setData({
      isHorizontal: !this.data.isHorizontal,
    }, function () {
      this.txTic.setOrientation(this.data.isHorizontal ? 'horizontal' : 'vertical');
    });
  },

  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      currentTab: tab,
    });
  },

  getPassword(e) {
    this.data.roomPassword = e.detail;
  },
  
  keyboardHeightChange (e) {
    this.setData({
      keyboard_height: e.detail.height,
    });
  },
  inputFocus (e) {
    this.setData({
      keyboard_height: e.detail.height,
    });
  },
  inputBlur (e) {
    this.setData({
      keyboard_height: 0,
    });
  },
});
